package com.heima.kafka.kafkastream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class KafkaStreamProcesser {
    public static void main(String[] args) {
        //设置kafka相关参数
        Properties properties = new Properties();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"streams-quickstart");

        //构建器
        StreamsBuilder streamsBuilder = new StreamsBuilder();

        //流式处理逻辑
        streamProcess(streamsBuilder);

        //kafkastream核心对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), properties);
        //开启kafka的流式处理
        kafkaStreams.start();
    }

    //流式处理的逻辑
    private static void streamProcess(StreamsBuilder streamsBuilder) {
        //创建kstream对象，同时指定从那个topic中接收消息
        KStream<String, String> stream = streamsBuilder.stream("itheima-stream-topic-input");
        /**
         * 处理消息的value
         */
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                //value就是接受到每一个消息的内容
                return Arrays.asList(value.split(" "));//将消息按空格拆分 存入集合返回
            }
        })
                //按照value进行聚合处理
                .groupBy((key,value)->value)//消息的键   value是拆分后的消息   就是apply方法返回集合中的单词
                //时间窗口 每10秒一个时间窗口，统计单词只统计本次10秒之内的消息
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //统计单词的个数
                .count()   //key:hello  value:2
                //转换为kStream
                .toStream()
                .map((key,value)->{
                    System.out.println("key:"+key+",vlaue:"+value);
                    return new KeyValue<>(key.key().toString(),value.toString());
                })//key:hello  value:"2"
                //发送消息   下游的topic值
                .to("itheima-stream-topic-out");
    }
}
